<template>
  <el-dialog v-if="load" destroy-on-close :close-on-click-modal="false" :title="form.shop_id ? '编辑Amazon店铺' : '添加Amazon店铺'" v-model="visible" align-center width="1200px"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :label-width="140">
      <div ref="firstTitle" class="v-title my-3">授权信息</div>
      <div class="grid grid-cols-3 gap-x-3">
        <el-form-item v-if="form.shop_id" label="真实店铺名" prop="real_shop_name">
          <el-input v-model="form.real_shop_name" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="店铺名" prop="shop_name" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.shop_name" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="平台账号（邮箱）" prop="email" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
          <el-input v-model="form.email" placeholder="请输入" :maxlength="200" />
        </el-form-item>
        <el-form-item label="开发者账号" prop="ad_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <div class="flex items-center w-full">
            <VSelect v-model="form.ad_id" placeholder="请选择" :options="developerOptions" class="w-full" />
            <div v-if="adInfo.tip === '已授权'" class="whitespace-nowrap ml-2 text-green-600">{{adInfo.tip}}</div>
            <div v-else class="whitespace-nowrap ml-2 text-red-600">{{adInfo.tip}}</div>
          </div>
        </el-form-item>
        <el-form-item label="授权区域" prop="auth_area" class="col-span-3">
          <div class="grid grid-cols-3 gap-x-3 w-full">
            <div>
              <VSelect v-model="form.auth_area" placeholder="请选择" :disabled="form.shop_id && form.sp_api_status === 1" :options="options.auth_area" class="w-full"
                @change="({ option }) => form.auth_area_tip = option.tip" />
            </div>
            <div class="flex items-center">
              <el-button type="primary" class="mr-3" @click="handleAuth">{{ form.shop_id && form.sp_api_status === 1 ? '更新授权' : '授权' }}</el-button>
              <small class="text-red-600 leading-4">点击登录亚马逊授权将跳转到亚马逊卖家后台，请在常用环境操作，避免关联</small>
            </div>
          </div>
          <small>{{ form.auth_area_tip }}</small>
        </el-form-item>
        <el-form-item label="店铺类型" prop="shop_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.shop_type" placeholder="请选择" :options="options.shop_type" class="w-full" />
        </el-form-item>
        <el-form-item label="默认品牌">
          <VSelect v-model="form.brand_ids" placeholder="请选择" :options="options.brand" multiple collapse-tags class="w-full" />
        </el-form-item>
        <el-form-item label="赛盒店铺ID" prop="saihe_shop_id">
          <el-input v-model="form.saihe_shop_id" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="前台访问地址ID">
          <el-input v-model="form.seller_id" placeholder="请输入" class="w-full" />
        </el-form-item>
        <div class="grid grid-cols-4 gap-x-3 col-span-2">
          <Status v-model="form" :options="options" />
        </div>
      </div>
      <el-divider />
      <div class="v-title my-3">分配信息</div>
      <div class="grid grid-cols-3 gap-x-3">
        <el-form-item label="首选业务员" prop="preferred_saleman_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VCascader v-model="form.preferred_saleman_id" placeholder="请选择" class="w-full" />
        </el-form-item>
        <el-form-item label="业务员">
          <VCascader v-model="form.salesman_ids" placeholder="请选择" multiple collapse-tags class="w-full" />
        </el-form-item>
        <el-form-item label="首选客服">
          <VCascader v-model="form.preferred_customer_service_id" placeholder="请选择" class="w-full" />
        </el-form-item>
        <el-form-item label="客服人员">
          <VCascader v-model="form.customer_service_id" placeholder="请选择" multiple collapse-tags class="w-full" />
        </el-form-item>
      </div>
      <el-divider />
      <div class="v-title my-3">注册信息</div>
      <div class="grid grid-cols-3 gap-x-3">
        <RegisterInfo ref="registerInfoRef" v-model="form" amazon />
      </div>
      <el-divider />
      <div class="v-title my-3">店铺销售范围</div>
      <div class="grid grid-cols-2 gap-x-3">
        <el-form-item label="产品类目">
          <div class="flex flex-col gap-3 w-full">
            <div v-for="(d, i) in form.product_category" :key="i" class="flex items-center">
              <VCascader v-model="d.external_id" placeholder="请选择" type="2" filterable clearable class="w-full flex-1" />
              <el-button v-if="!i" link icon="circlePlus" class="text-lg" @click="form.product_category.push({ external_id: 0 })"></el-button>
              <el-button v-else link icon="remove" class="text-lg" @click="form.product_category.splice(i, 1)"></el-button>
            </div>
          </div>
        </el-form-item>
        <!-- <el-form-item label="平台类目">
          <VCascader v-model="form.field" placeholder="请选择" type="2" filterable clearable class="w-full" />
        </el-form-item> -->
      </div>
      <el-divider />
      <div class="v-title my-3">资料信息</div>
      <Company v-model="form" :options="options" :detail="api.companyDetail" />
      <el-form-item label="VAT税号">
        <TableAdd v-model="form.vat_info" type="vat" :options="options" />
      </el-form-item>
      <el-form-item label="EPR">
        <TableAdd v-model="form.epr" type="epr" :options="options" />
      </el-form-item>
      <el-divider />
      <div class="v-title my-3">信用卡信息</div>
      <TableAdd v-model="form.credit_card" type="credit" :options="options" />
      <el-divider />
      <div class="v-title my-3">收款卡信息</div>
      <TableAdd v-model="form.collect_card" type="collect" :options="options" />
      <el-divider />
      <div class="v-title my-3">紫鸟信息</div>
      <Ziniao v-model="form.ziniao_info" :options="options" />
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import TableAdd from '../../TableAdd'
import Company from '../../Company'
import Status from '../../Status'
import RegisterInfo from '../../RegisterInfo'
import Ziniao from '../../Ziniao'
import { ElMessage, ElMessageBox } from 'element-plus'
import XEUtils, { clone } from 'xe-utils'
import { computed } from "vue";
import { getOption } from '@/api/public'
import { handleLink } from './utils'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

const ziniaoContactPerson = computed(() => {
  const account = form.value.ziniao_info.account
  if (props.options && account) {
    const item = props.options.ziniao_account.find(v => v.value === account)
    return item.contact_person
  }
  return null
})

// 打开弹窗
const firstTitle = ref()
const developerOptions = ref([])
const registerInfoRef = ref()
const adInfo = computed(() => developerOptions.value.find(d => d.value === form.value.ad_id) || {})
const open = async (shop_id) => {
  if (!load.value) {
    load.value = true
    await 1
  }

  await getOption({ type: 'shop_amazon', shop_id }).then(res => {
    developerOptions.value = res.data.developer
  })
  // 编辑
  if (shop_id) {
    const res = await api.detail({ shop_id })
    form.value = res.data
    const { options } = props
    form.value.vat_info = form.value.vat_info.map(d => {
      const item = options.vat.find(c => c.vat_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, vat_num: '信息已失效' }
    })
    form.value.credit_card = form.value.credit_card.map(d => {
      const item = options.credit_card.find(c => c.card_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, bank_name: '信息已失效' }
    })
    form.value.collect_card = form.value.collect_card.map(d => {
      const item = options.collect_card.find(c => c.card_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, collect_type: '信息已失效' }
    })
    form.value.epr = form.value.epr.map(d => {
      const item = options.epr.find(c => c.epr_id === d.external_id)
      if (item) return { ...d, ...item }
      return { ...d, certificate_id: '信息已失效' }
    })
    if (!form.value.product_category || !form.value.product_category.length) {
      form.value.product_category.push({ external_id: '' })
    }
  } else { //新增
    form.value = {
      refresh_token: '',
      email_password: '',
      account_password: '',
      verify_image: [],
      "shop_name": "",
      "shop_site_coe": "",
      "email": "",
      "ad_id": null,
      "auth_area": "",
      "shop_type": null,
      "brand_ids": [],
      "saihe_shop_id": '',
      "seller_id": "",
      "status": 2,
      is_download_orders: 1,
      is_pre_generate: 1,
      is_platform_shipment: 1,
      "preferred_saleman_id": null,
      "salesman_ids": [],
      "customer_service_id": [],
      "phone_id": null,
      "product_category": [{ external_id: "" }],
      "platform_category": [],
      "company_id": null,
      "company": {
        "company_id": '',
        "company_name_ch": "",
        "company_name_py": "",
        "license_num": "",
        "established_date": "",
        "company_area_names": "",
        "company_address_detail": "",
        "company_address_pinyin": "",
        "postal_code": "",
        "legal_person_name": "",
        "legal_person_idcard": "",
        "legal_person_mobile": "",
        "public_bank": "",
        "bank_branch": "",
        "bank_account_num": ""
      },
      "vat_info": [],
      "epr_id": 0,
      "epr": [],
      "credit_card": [],
      "collect_card": [],
      "ziniao_info": {
        "account": 0,
        "ip": "",
        "period": 0,
        "renewal_time": ""
      }
    }
    const { options, shop_type } = props
    if (options.developer && Array.isArray(options.developer) && options.developer.length > 0) {
      form.value.ad_id = options.developer[0].value
    }
  }
  loadings = reactive({})
  visible.value = true
  nextTick(() => {
    formRef?.value.clearValidate()
    firstTitle?.value.scrollIntoView()
    registerInfoRef?.value.reset()
  })
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  registerInfoRef?.value.clearTimer()
}

// 授权
const handleAuth = () => {
  const origin = window.location.origin
  const { ad_id, auth_area, shop_id } = form.value
  handleLink({ origin, ad_id, auth_area, shop_id }, {
    success: (val) => {
      form.value = { ...form.value, ...val }
    }
  })
}

// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  const cloneForm = clone(form.value, true)
  cloneForm.product_category = cloneForm.product_category.filter(v => v.external_id)
  api[form.value.shop_id ? 'edit' : 'create'](cloneForm).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>